package com.itlong.cloud.miniprogram.service.impl;

import com.itlong.cloud.POJO.DTO.app.MiniScanQrCodePassDTO;
import com.itlong.cloud.POJO.VO.app.AppDoorDevicesVO;
import com.itlong.cloud.POJO.VO.app.AppFloorDevicesVO;
import com.itlong.cloud.POJO.VO.miniprogram.MiniProgramMyEquipListVO;
import com.itlong.cloud.POJO.VO.miniprogram.MiniProgramUserRoomInfoVO;
import com.itlong.cloud.POJO.VO.operate.OperateDeviceQRCodeInfoVO;
import com.itlong.cloud.app.dao.IAppDeviceDao;
import com.itlong.cloud.app.service.IAppDeviceService;
import com.itlong.cloud.miniprogram.service.IMiniProgramEquipService;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <desc>
 *      小程序-固件升级-设备接口实现类。
 * <desc/>
 *
 * @createDate 2018/11/27.
 */
@Service
public class IMiniProgramEquipServiceImpl implements IMiniProgramEquipService {

    private static final Logger LOG = LoggerFactory.getLogger(IMiniProgramEquipServiceImpl.class);

    @Autowired
    IAppDeviceService iAppDeviceService;

    @Autowired
    IAppDeviceDao iAppDeviceDao;

    /**
     * <desc>
     *      获取用户所有设备
     * </desc>
     *
     * @param userId 用户编号
     * @param projectId 项目编号
     * @return
     * @author Qiang.S
     * @createDate 2018/11/27
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<MiniProgramMyEquipListVO> myEquipInfo(String userId,String projectId) throws Exception{
        List<AppDoorDevicesVO> doorList = iAppDeviceService.getDoorDevices(userId,projectId,1);//获取门禁设备
        List<AppFloorDevicesVO> floorList = iAppDeviceService.getFloorDevices(userId,projectId,1);//获取电梯设备
        List<String> floorDeviceUniqueList = new ArrayList<>();
        for (AppFloorDevicesVO appFloorDevicesVO : floorList) {
            floorDeviceUniqueList.add(appFloorDevicesVO.getDeviceUnique());
            //逆序排列常用楼层和公共楼层
            appFloorDevicesVO.setLiveFloor(StringHandlerUtil.getReverseStr(appFloorDevicesVO.getLiveFloor()));
            appFloorDevicesVO.setLiveLogicalFloor(StringHandlerUtil.getReverseStr(appFloorDevicesVO.getLiveLogicalFloor()));
            appFloorDevicesVO.setCommonFloor(StringHandlerUtil.getReverseStr(appFloorDevicesVO.getCommonFloor()));
            appFloorDevicesVO.setCommonLogicalFloor(StringHandlerUtil.getReverseStr(appFloorDevicesVO.getCommonLogicalFloor()));

        }
        // 获取游客模式下有公共楼层的电梯设备
        List<AppFloorDevicesVO> floorGuestList = iAppDeviceDao.getGuestFloorList(projectId);
        if (floorGuestList != null && !floorGuestList.isEmpty()) {
            List<String> controllerDevices = new ArrayList<>();
            floorList.forEach(floor -> controllerDevices.add(floor.getDeviceUnique()));
            floorGuestList.forEach(floor -> controllerDevices.add(floor.getDeviceUnique()));
            for (AppFloorDevicesVO appFloorDevicesVO : floorGuestList) {
                if (!floorDeviceUniqueList.contains(appFloorDevicesVO.getDeviceUnique())) {
                    // 检索电梯是否是云电梯，如果是则查询是否绑定控制器
                    if (StringUtils.isNotBlank(appFloorDevicesVO.getLiftType()) && !appFloorDevicesVO.getLiftType().equals("1")) {
                        Map<String, Object> controllers = iAppDeviceDao.getControllerDeviceUniqueByElevatorDeviceUniques(appFloorDevicesVO.getDeviceUnique(), controllerDevices.toArray(new String[controllerDevices.size()]));
                        if (controllers != null && controllers.get("groupConId") != null) {
                            if (!controllers.get("status").toString().equals("1")) {
                                continue;
                            }
                            appFloorDevicesVO.setGroupConId(controllers.get("groupConId").toString());
                            appFloorDevicesVO.setRelatedDeviceId(controllers.get("deviceUnique").toString());
                        }
                    }
                    appFloorDevicesVO.setFloorAuth(StringHandlerUtil.filterLastComma(StringHandlerUtil.getAuthCodeBynNturalFloors("")).toUpperCase());
                    appFloorDevicesVO.setValiTime(DateUtil.formatStringToDate(StringHandlerUtil.filterLastComma("2099-12-31 23:59:59"), DateUtil.DATE_FORMAT_TYPE1).getTime() + "");
                    floorList.add(appFloorDevicesVO);
                    floorDeviceUniqueList.add(appFloorDevicesVO.getDeviceUnique());
                }
            }
        }
        //处理没有有效批次号的设备，随同项目最近批次号过期而过期的标识
        boolean mark = false;
        //需要排除的旧批次号集合
        List<String> oldBatchNumberArr = new ArrayList<>();
        //查询出需排除的旧批次集合
        List<String> oldBatchNumberList = iAppDeviceDao.getOldBatchNumberByProjectId(projectId);
        for(String oldBatchNumbers : oldBatchNumberList){
            for(String oldBatchNumber : oldBatchNumbers.split(",")){
                oldBatchNumberArr.add(oldBatchNumber);
            }
        }
        //获取项目下最近批次号过期时间
        String endTimeByProjectId = iAppDeviceDao.getBatchNumberEndTimeByProjectId(projectId,oldBatchNumberArr.size()>0?oldBatchNumberArr:null);
        if(StringUtils.isNotEmpty(endTimeByProjectId)){
            Date endDate = DateUtil.fomatLongDate2(endTimeByProjectId);
            Date nowDate = DateUtil.fomatLongDate2(DateUtil.fomatDate(new Date(), "yyyy-MM-dd"));
            Integer endDays = DateUtil.differentDays(nowDate, endDate);
            if (endDays < -3) {
                mark = true;
            }
        }
        List<MiniProgramMyEquipListVO> list = new ArrayList<>();
        for (AppDoorDevicesVO appDoorDevicesVO:doorList) {
            MiniProgramMyEquipListVO miniProgramMyEquipListVO = new MiniProgramMyEquipListVO();
            miniProgramMyEquipListVO.setDeviceName(appDoorDevicesVO.getDeviceName());
            miniProgramMyEquipListVO.setDeviceKind("2");//门禁
            miniProgramMyEquipListVO.setDeviceUnique(appDoorDevicesVO.getDeviceUnique());
            miniProgramMyEquipListVO.setProtocolVersion(appDoorDevicesVO.getProtocolVersion());
            miniProgramMyEquipListVO.setThreshold(appDoorDevicesVO.getThreshold());
            miniProgramMyEquipListVO.setDoorAuth(appDoorDevicesVO.getDoorAuth());
            miniProgramMyEquipListVO.setCardNum(appDoorDevicesVO.getCardNum());
            miniProgramMyEquipListVO.setValiTime(appDoorDevicesVO.getValiTime());
            miniProgramMyEquipListVO.setPosition(appDoorDevicesVO.getPosition());
            miniProgramMyEquipListVO.setDoorType(appDoorDevicesVO.getDoorType());
            //如果批次号不为空，则查询其对应的过期时间
            if(StringUtils.isNotEmpty(appDoorDevicesVO.getBatchNumber())){
                String endTime = iAppDeviceDao.getBatchNumberEndTime(appDoorDevicesVO.getBatchNumber());
                if(StringUtils.isNotEmpty(endTime)){
                    Date endDate = DateUtil.fomatLongDate2(endTime);
                    Date nowDate = DateUtil.fomatLongDate2(DateUtil.fomatDate(new Date(), "yyyy-MM-dd"));
                    Integer endDays = DateUtil.differentDays(nowDate, endDate);
                    if (endDays < -3) {
                        continue;
                    }
                }else{
                    if(mark){
                        continue;
                    }
                }
            }else{
                if(mark){
                    continue;
                }
            }
            list.add(miniProgramMyEquipListVO);
        }
        for (AppFloorDevicesVO appFloorDevicesVO:floorList) {
            MiniProgramMyEquipListVO miniProgramMyEquipListVO = new MiniProgramMyEquipListVO();
            miniProgramMyEquipListVO.setDeviceName(appFloorDevicesVO.getDeviceName());
            if (appFloorDevicesVO.getLiftType() != null) {
                //如果批次号不为空，则查询其对应的过期时间
                if(StringUtils.isNotEmpty(appFloorDevicesVO.getBatchNumber())){
                    String endTime = iAppDeviceDao.getBatchNumberEndTime(appFloorDevicesVO.getBatchNumber());
                    if(StringUtils.isNotEmpty(endTime)){
                        Date endDate = DateUtil.fomatLongDate2(endTime);
                        Date nowDate = DateUtil.fomatLongDate2(DateUtil.fomatDate(new Date(), "yyyy-MM-dd"));
                        Integer endDays = DateUtil.differentDays(nowDate, endDate);
                        if (endDays < -3) {
                            continue;
                        }
                    }else{
                        if(mark){
                            continue;
                        }
                    }
                }else{
                    if(mark){
                        continue;
                    }
                }
                miniProgramMyEquipListVO.setCommonFloor(appFloorDevicesVO.getCommonFloor());
                miniProgramMyEquipListVO.setCommonLogicalFloor(appFloorDevicesVO.getCommonLogicalFloor());
                miniProgramMyEquipListVO.setLiveFloor(appFloorDevicesVO.getLiveFloor());
                miniProgramMyEquipListVO.setLiveLogicalFloor(appFloorDevicesVO.getLiveLogicalFloor());
                miniProgramMyEquipListVO.setProtocolVersion(appFloorDevicesVO.getProtocolVersion());
                miniProgramMyEquipListVO.setThreshold(appFloorDevicesVO.getThreshold());
                miniProgramMyEquipListVO.setFloorAuth(appFloorDevicesVO.getFloorAuth());
                miniProgramMyEquipListVO.setGroupConId(appFloorDevicesVO.getGroupConId());
                miniProgramMyEquipListVO.setRelatedDeviceId(appFloorDevicesVO.getRelatedDeviceId());
                miniProgramMyEquipListVO.setFloors(appFloorDevicesVO.getFloors());
                miniProgramMyEquipListVO.setFloorsName(appFloorDevicesVO.getFloorsName());
                miniProgramMyEquipListVO.setBlueToothCallStandard(appFloorDevicesVO.getBlueToothCallStandard());
                if ("1".equals(appFloorDevicesVO.getLiftType())) {//1为蓝牙电梯
                    miniProgramMyEquipListVO.setDeviceKind("11");
                }
                if ("2".equals(appFloorDevicesVO.getLiftType())) {//2为云电梯
                    miniProgramMyEquipListVO.setDeviceKind("12");
                }
                if ("1,2".equals(appFloorDevicesVO.getLiftType())) {//1 2都有分成2条返回
                    miniProgramMyEquipListVO.setDeviceKind("11");
                    miniProgramMyEquipListVO.setDeviceUnique(appFloorDevicesVO.getDeviceUnique());
                    list.add(miniProgramMyEquipListVO);
                    MiniProgramMyEquipListVO miniProgramMyEquipListVO2 = new MiniProgramMyEquipListVO();
                    miniProgramMyEquipListVO2.setDeviceUnique(appFloorDevicesVO.getDeviceUnique());
                    miniProgramMyEquipListVO2.setDeviceName(appFloorDevicesVO.getDeviceName());
                    miniProgramMyEquipListVO2.setDeviceKind("12");
                    miniProgramMyEquipListVO2.setCommonFloor(appFloorDevicesVO.getCommonFloor());
                    miniProgramMyEquipListVO2.setCommonLogicalFloor(appFloorDevicesVO.getCommonLogicalFloor());
                    miniProgramMyEquipListVO2.setLiveFloor(appFloorDevicesVO.getLiveFloor());
                    miniProgramMyEquipListVO2.setLiveLogicalFloor(appFloorDevicesVO.getLiveLogicalFloor());
                    miniProgramMyEquipListVO2.setProtocolVersion(appFloorDevicesVO.getProtocolVersion());
                    miniProgramMyEquipListVO2.setThreshold(appFloorDevicesVO.getThreshold());
                    miniProgramMyEquipListVO2.setFloorAuth(appFloorDevicesVO.getFloorAuth());
                    miniProgramMyEquipListVO2.setGroupConId(appFloorDevicesVO.getGroupConId());
                    miniProgramMyEquipListVO2.setRelatedDeviceId(appFloorDevicesVO.getRelatedDeviceId());
                    miniProgramMyEquipListVO2.setFloors(appFloorDevicesVO.getFloors());
                    miniProgramMyEquipListVO2.setFloorsName(appFloorDevicesVO.getFloorsName());
                    miniProgramMyEquipListVO2.setBlueToothCallStandard(appFloorDevicesVO.getBlueToothCallStandard());
                    list.add(miniProgramMyEquipListVO2);
                    continue;
                }
            }
            miniProgramMyEquipListVO.setDeviceUnique(appFloorDevicesVO.getDeviceUnique());
            //排序--常用公共楼层和常用楼层选择列表倒叙排列
            list.add(miniProgramMyEquipListVO);
        }
        return list;
    }

    /**
     * <desc>
     *      获取用户项目下的设备过期情况
     * </desc>
     *
     * @param userId 用户编号
     * @param projectId 项目编号
     * @return 1代表全部设备正常 2代表设备即将到期（0-3天） 3代表部分设备已过期3天  4代表全部设备已过期3天
     * @author Juguang.S
     * @createDate 2019/11/27
     */
    public String getUserDeviceExpiredInfo(String userId,String projectId) throws Exception{
        List<AppDoorDevicesVO> doorList = iAppDeviceService.getDoorDevices(userId,projectId,1);//获取门禁设备
        List<AppFloorDevicesVO> floorList = iAppDeviceService.getFloorDevices(userId,projectId,1);//获取电梯设备
        boolean mark = false;
        //需要排除的旧批次号集合
        List<String> oldBatchNumberArr = new ArrayList<>();
        //查询出需排除的旧批次集合
        List<String> oldBatchNumberList = iAppDeviceDao.getOldBatchNumberByProjectId(projectId);
        for(String oldBatchNumbers : oldBatchNumberList){
            for(String oldBatchNumber : oldBatchNumbers.split(",")){
                oldBatchNumberArr.add(oldBatchNumber);
            }
        }
        //获取项目下最近批次号过期时间
        String endTimeByProjectId = iAppDeviceDao.getBatchNumberEndTimeByProjectId(projectId,oldBatchNumberArr.size()>0?oldBatchNumberArr:null);
        //过期0-3天内的数量
        int count = 0;
        //过期超过3天的数量
        int disableCount = 0;
        //有批次号的数量
        int batchNumberCount = 0;
        Date nowDate = DateUtil.fomatLongDate2(DateUtil.fomatDate(new Date(), "yyyy-MM-dd"));
        for (AppDoorDevicesVO appDoorDevicesVO:doorList) {
            //如果批次号不为空，则查询其对应的过期时间
            if(StringUtils.isNotEmpty(appDoorDevicesVO.getBatchNumber())){
                String endTime = iAppDeviceDao.getBatchNumberEndTime(appDoorDevicesVO.getBatchNumber());
                if(StringUtils.isNotEmpty(endTime)){
                    batchNumberCount++;
                    Date endDate = DateUtil.fomatLongDate2(endTime);
                    Integer endDays = DateUtil.differentDays(nowDate, endDate);
                    if (endDays < -3) {
                        disableCount++;
                        continue;
                    }
                    if (endDays >= -3 && endDays < 0) {
                        count++;
                    }
                }else{
                    if(StringUtils.isNotEmpty(endTimeByProjectId)){
                        Date endDate = DateUtil.fomatLongDate2(endTimeByProjectId);
                        Integer endDays = DateUtil.differentDays(nowDate, endDate);
                        if (endDays < -3) {
                            mark = true;
                        }
                        if (endDays >= -3 && endDays < 0) {
                            count++;
                        }
                    }
                }
            }else{
                if(StringUtils.isNotEmpty(endTimeByProjectId)){
                    Date endDate = DateUtil.fomatLongDate2(endTimeByProjectId);
                    Integer endDays = DateUtil.differentDays(nowDate, endDate);
                    if (endDays < -3) {
                        mark = true;
                    }
                    if (endDays >= -3 && endDays < 0) {
                        count++;
                    }
                }
            }
        }
        for (AppFloorDevicesVO appFloorDevicesVO:floorList) {
            //如果批次号不为空，则查询其对应的过期时间
            if(StringUtils.isNotEmpty(appFloorDevicesVO.getBatchNumber())){
                String endTime = iAppDeviceDao.getBatchNumberEndTime(appFloorDevicesVO.getBatchNumber());
                if(StringUtils.isNotEmpty(endTime)){
                    batchNumberCount++;
                    Date endDate = DateUtil.fomatLongDate2(endTime);
                    Integer endDays = DateUtil.differentDays(nowDate, endDate);
                    if (endDays < -3) {
                        disableCount++;
                        continue;
                    }
                    if (endDays >= -3 && endDays < 0) {
                        count++;
                    }
                }else{
                    if(StringUtils.isNotEmpty(endTimeByProjectId)){
                        Date endDate = DateUtil.fomatLongDate2(endTimeByProjectId);
                        Integer endDays = DateUtil.differentDays(nowDate, endDate);
                        if (endDays < -3) {
                            mark = true;
                        }
                        if (endDays >= -3 && endDays < 0) {
                            count++;
                        }
                    }
                }
            }else{
                if(StringUtils.isNotEmpty(endTimeByProjectId)){
                    Date endDate = DateUtil.fomatLongDate2(endTimeByProjectId);
                    Integer endDays = DateUtil.differentDays(nowDate, endDate);
                    if (endDays < -3) {
                        mark = true;
                    }
                    if (endDays >= -3 && endDays < 0) {
                        count++;
                    }
                }
            }
        }
        if(count == 0 && disableCount == 0 && !mark){
            return "1";
        }else if((batchNumberCount==disableCount && mark ) ||
                (doorList!=null && floorList!=null &&  doorList.size()+floorList.size()==disableCount) ||
                (doorList==null && floorList!=null &&  floorList.size()==disableCount) ||
                (doorList!=null && floorList==null &&  doorList.size()==disableCount)){
            return "4";
        }else if(disableCount>0 || mark){
            return "3";
        }else{
            return "2";
        }
    }

    /**
     * <desc>
     *      获取二维码相关信息，包含绑定的设备
     * </desc>
     *
     * @author wangzhi
     * @createDate 2020/02/26
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public OperateDeviceQRCodeInfoVO getQrCodeInfo(MiniScanQrCodePassDTO miniScanQrCodePassDTO) throws Exception {
        OperateDeviceQRCodeInfoVO qrCodeInfo = iAppDeviceDao.getQrCodeInfo(miniScanQrCodePassDTO);
        if (qrCodeInfo != null) {
            List<String> controllerDevices = new ArrayList<>();
            controllerDevices.add(qrCodeInfo.getDeviceUnique());
            Map<String, Object> controllers = iAppDeviceDao.getControllerDeviceUniqueByElevatorDeviceUniques(qrCodeInfo.getDeviceUnique(), controllerDevices.toArray(new String[controllerDevices.size()]));
            if (controllers != null && controllers.get("groupConId") != null) {
                if (!"1".equals(controllers.get("status").toString())) {
                    return null;
                }
                qrCodeInfo.setGroupConId(controllers.get("groupConId").toString());
            }
        }
        return qrCodeInfo;
    }

    /**
     * <desc>
     *      根据设备唯一码获取地址信息
     * </desc>
     *
     * @param deviceUnique 设备唯一码
     * @return
     * @author Juguang.S
     * @createDate 2020/03/24
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<MiniProgramUserRoomInfoVO> getAddressByDeviceUnique(String deviceUnique) throws Exception {
        if(deviceUnique.substring(8,9).equals("1")){
            return iAppDeviceDao.getAddressByDeviceUnique(deviceUnique);
        }else{
            return iAppDeviceDao.getAddressByEntranceDeviceUnique(deviceUnique);
        }

    }

    /**
     * <desc>
     *      根据楼栋ID查询单元信息
     * </desc>
     *
     * @param buildId 楼栋ID
     * @return
     * @author Juguang.S
     * @createDate 2020/03/24
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<Map<String,String>> getUnitInfoByBuildId(String buildId,String deviceUnique) throws Exception {
        if(deviceUnique.substring(8,9).equals("1")){
            return iAppDeviceDao.getUnitInfoByBuildIdByElevator(buildId,deviceUnique);
        }else{
            return iAppDeviceDao.getUnitInfoByBuildIdByEntrance(buildId,deviceUnique);
        }

    }

    /**
     * <desc>
     *      获取电梯的公共楼层
     * </desc>
     *
     * @author wangzhi
     * @createDate 2020/04/30
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Map<String, Object> getElevatorCommonFloor(String deviceUnique) throws Exception {
        return iAppDeviceDao.getElevatorCommonFloor(deviceUnique);
    }

}
